package com.chatroom.client.ui;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class UserManager {
    private static final String USER_FILE = "users.txt";
    private static UserManager instance = new UserManager();
    private Map<String, String> userMap = new HashMap<>();

    private UserManager() {
        loadUsers();
    }

    public static UserManager getInstance() {
        return instance;
    }

    public boolean registerUser(String username, String password) {
        if (userMap.containsKey(username)) return false;
        userMap.put(username, password);
        saveUsers();
        return true;
    }

    public boolean validateUser(String username, String password) {
        return password.equals(userMap.get(username));
    }

    private void loadUsers() {
        File file = new File(USER_FILE);
        if (!file.exists()) return;
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), java.nio.charset.StandardCharsets.UTF_8))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 2) {
                    userMap.put(parts[0], parts[1]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void saveUsers() {
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(USER_FILE), java.nio.charset.StandardCharsets.UTF_8))) {
            for (Map.Entry<String, String> entry : userMap.entrySet()) {
                bw.write(entry.getKey() + "," + entry.getValue());
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 